package io.github.stary1993.kite.admin.config;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import io.github.stary1993.kite.admin.entity.SysRole;
import io.github.stary1993.kite.admin.service.SysUserService;
import io.github.stary1993.kite.admin.vo.UserVO;
import io.github.stary1993.kite.core.constant.CommonConstants;
import io.github.stary1993.kite.core.constant.SecurityConstants;
import io.github.stary1993.kite.security.core.SecurityUser;
import io.github.stary1993.kite.security.support.SecurityUserDetailsService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.*;

/**
 * 用户详细信息
 *
 * @author lengleng hccake
 */
@Slf4j
@RequiredArgsConstructor
public class AppUserDetailsService implements SecurityUserDetailsService {

	private final SysUserService sysUserService;


	/**
	 * 手机号登录
	 * @param phone 手机号
	 * @return
	 */
	@Override
	@SneakyThrows
	public UserDetails loadUserByUsername(String phone) {
		UserVO userVO = sysUserService.detailsByPhone(phone);
		List<SysRole> roleList = userVO.getRoleList();
		List<String> permissions = new ArrayList<>();
		Set<String> dbAuthsSet = new HashSet<>();

		if (ArrayUtil.isNotEmpty(userVO.getRoleList())) {
			// 获取角色
			roleList.forEach(role -> dbAuthsSet.add(SecurityConstants.ROLE + role.getRoleCode()));
			// 获取资源
			dbAuthsSet.addAll(permissions);
		}

		Collection<GrantedAuthority> authorities = AuthorityUtils
				.createAuthorityList(dbAuthsSet.toArray(new String[0]));
		return new SecurityUser(userVO.getUserId(),
				userVO.getUsername(),
				SecurityConstants.BCRYPT + userVO.getPassword(),
				userVO.getPhone(),
				true,
				true,
				true,
				StrUtil.equals(userVO.getLockFlag(), CommonConstants.STATUS_NORMAL),
				authorities);
	}


	/**
	 * 是否支持此客户端校验
	 * @param clientId 目标客户端
	 * @return true/false
	 */
	@Override
	public boolean support(String clientId, String grantType) {
		return SecurityConstants.MOBILE.equals(grantType);
	}

}
